package com.study.demomongo;

import com.study.demomongo.entity.User;
import com.study.demomongo.repository.UserRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.regex.Pattern;

@SpringBootTest
class DemomongoApplicationRepo {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserRepository userRepository;

    @Test
    void contextLoads() {
        final User user = new User();
        user.setAge(28);
        user.setEmail("qq@qq.com");
        user.setName("qs");
        userRepository.insert(user);
        System.out.println(user);
    }

    @Test
    public void findAll() {
        final List<User> all = mongoTemplate.findAll(User.class);
        all.forEach(System.out::println);

        final User byId = mongoTemplate.findById("", User.class);
        System.out.println(byId);
    }

    /**
     * 条件查询
     */
    @Test
    public void findUserList() {
        //name = test and age =20
        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        final User user = new User();
        user.setAge(28);
        user.setName("t");
        Example<User> example = Example.of(user, matcher);
        final List<User> userList = userRepository.findAll(example);
        userList.forEach(us -> {
            System.out.println(us);
        });
    }

    /**
     * 条件查询
     */
    @Test
    public void findUserListLike() {
        //name like %test% and age =20
        String name = "est";
        String regex = String.format("%s%s%s", "^.*", name, ".*$");
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Query query = new Query();
        query.addCriteria(Criteria.where("name").regex(pattern));
        final List<User> userList = mongoTemplate.find(query, User.class);

        userList.forEach(user -> {
            System.out.println(user);
        });

        // String name = "est";
        // String regex = String.format("%s%s%s", "^.*", name, ".*$");
        // Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        // Query query = new Query(Criteria.where("name").regex(pattern));
        // List<User> userList = mongoTemplate.find(query, User.class);

    }
}
